package com.yazi.mxz.person.controller.shop;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.jackson.result.ListResult;
import com.myframework.smhj.jackson.result.ObjectResult;
import com.myframework.smhj.jackson.result.StatusResult;
import com.yazi.mxz.common.entity.beans.SpecType;
import com.yazi.mxz.common.service.SpecTypeService;
import com.yazi.mxz.person.data.form.shop.SpecTypeForm;
import com.yazi.mxz.person.jackson.filter.SpecTypeFilter;

/**
 * 商品规格类型
 *
 * @author mo_yq5
 * @since 2016年6月1日
 */
@Controller("shop-specTypeController")
@RequestMapping("/shop/specType")
public class SpecTypeController extends BaseController {
	private static Logger log = LoggerFactory.getLogger(SpecTypeController.class);
	
	@Resource
	SpecTypeService specTypeService;
	
	@RequestMapping("/list/json")
	@ResponseBody
	public ListResult<?> listJson(Long catId, Long storeGoodsId) {
		log.debug("获取商品规格类型列表: catId={}, storeGoodsId={}", catId, storeGoodsId);
		ListResult<SpecType> jsonResult = new ListResult<SpecType>();
		jsonResult.setFilter(SpecTypeFilter.getWithSpecs());
		try {
			jsonResult.setResult(specTypeService.list(catId, storeGoodsId));
			jsonResult.setOk();
		} catch (Exception e) {
			log.error("获取商品规格类型列表异常：", e);
			jsonResult.setErrorMessage(e.getMessage());
		}
		
		return jsonResult;
	}
	
	@RequestMapping("/addDo/json")
	@ResponseBody
	public ObjectResult<?> addDoJson(@Validated(SpecTypeForm.Add.class) SpecTypeForm form) throws MyException {
		SpecType specType = form.get();
		log.debug("添加商品规格类型: name={}", specType.getName());
		ObjectResult<Long> jsonResult = new ObjectResult<Long>();
		try {
			specType = specTypeService.addOrEditByStore(getStore(), specType);
			jsonResult.setResult(specType.getSpecTypeId());
			jsonResult.setOk();
		} catch (Exception e) {
			log.error("添加商品规格类型异常：", e);
			jsonResult.setErrorMessage(e.getMessage());
		}
		
		return jsonResult;
	}
	
	@RequestMapping("/editDo/json")
	@ResponseBody
	public StatusResult editDoJson(@Validated(SpecTypeForm.Edit.class) SpecTypeForm form) {
		SpecType specType = form.get();
		log.debug("编辑商品规格类型: specTypeId={}, name={}", specType.getSpecTypeId(), specType.getName());
		StatusResult jsonResult = new StatusResult();
		try {
			// 设定为：只能修改名称
			SpecType dest = specTypeService.one(specType.getSpecTypeId());
			dest.setName(specType.getName());
			specTypeService.merge(dest);
			jsonResult.setOk();
		} catch (Exception e) {
			log.error("编辑商品规格类型异常：", e);
			jsonResult.setErrorMessage(e.getMessage());
		}
		
		return jsonResult;
	}
}
